//
//  UIViewController+SKViolentClick.m
//  skhr
//
//  Created by sujeking on 2018/10/25.
//  Copyright © 2018年 sujeking. All rights reserved.
//

#import "UIViewController+SKViolentClick.h"
#import <objc/message.h>

#define kPreventRepeatClickTime(_seconds_) \
static BOOL shouldPrevent; \
if (shouldPrevent) return; \
shouldPrevent = YES; \
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((_seconds_) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ \
shouldPrevent = NO; \
}); \


@implementation UITableView (SKViolentClick)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL setDelegate = NSSelectorFromString(@"setDelegate:");
        Method originalMethod = class_getInstanceMethod(self, setDelegate);
        Method swizzledMethod = class_getInstanceMethod(self, @selector(sksetDelegate:));

        BOOL didAddMethod =
        class_addMethod(self,
                        @selector(setDelegate:),
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(self,
                                @selector(sksetDelegate:),
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
             method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)sksetDelegate:(id<UITableViewDelegate>)delegate {
    [self sksetDelegate:delegate];
    
    if (class_addMethod([delegate class], NSSelectorFromString(@"skdidSelectRowAtIndexPath"), (IMP)skdidSelectRowAtIndexPath, "v@:@@")) {
        Method didSelectOriginalMethod = class_getInstanceMethod([delegate class], NSSelectorFromString(@"skdidSelectRowAtIndexPath"));
        Method didSelectSwizzledMethod = class_getInstanceMethod([delegate class], @selector(tableView:didSelectRowAtIndexPath:));
        
        method_exchangeImplementations(didSelectOriginalMethod, didSelectSwizzledMethod);
    }
}

void skdidSelectRowAtIndexPath(id self, SEL _cmd, id tableView, id indexPath)
{
    SEL selector = NSSelectorFromString(@"skdidSelectRowAtIndexPath");
    ((void(*)(id, SEL, id, id))objc_msgSend)(self, selector, tableView, indexPath);
    kPreventRepeatClickTime(0.5);
}



@end
